package com.ndood.admin.repository.system.manager;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Repository;

import com.ndood.admin.core.jpa.entitymanager.EntityManagerModel;
import com.ndood.admin.pojo.system.dto.LogDto;

/**
 * 系统日志持久化管理类
 */
@Repository
@SuppressWarnings("unchecked")
public class LogRepositoryManager {
	
	@Autowired
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 查询出日志分页信息
	 */
	public Page<LogDto> pageLogList(String keywords, Date startTime, Date endTime, Integer pageNo, Integer pageSize) {

		// Step1: 动态拼接jpql
		EntityManagerModel model = EntityManagerModel.newModel();
		if(!StringUtils.isBlank(keywords)) {
			model.plusSQL("AND s.username LIKE :username ").plusParam("username", "%"+keywords+"%");
		}
		if(startTime!=null) {
			model.plusSQL("AND s.createTime >= :startTime ").plusParam("startTime", startTime);
		}
		if(endTime!=null) {
			model.plusSQL("AND s.createTime < :endTime ").plusParam("endTime", endTime);
		}
		
		// Step2: 获取list
		Query query = em.createQuery("SELECT new com.ndood.admin.pojo.system.dto.LogDto(s.recordNo, s.ip, s.ipInfo, s.requestType, s.requestUrl, s.requestParam, " + 
				" s.staffId, s.staffName, s.createTime, s.updateTime) "
				+ "FROM LogPo s "
				+ "WHERE 1 = 1 " + model.getSQLPlus()
				+ "ORDER BY s.createTime DESC ");
		
		model.setQueryParam(query);
		query.setFirstResult(pageNo * pageSize).setMaxResults(pageSize);
		query.setHint("org.hibernate.cacheable", true);
		List<LogDto> resultList = query.getResultList();
		
		// Step3: 获取count
		Query queryCount = em.createQuery("SELECT COUNT(0) "
				+ "FROM LogPo s "
				+ "WHERE 1 = 1 " + model.getSQLPlus());

		model.setQueryParam(queryCount);
		queryCount.setHint("org.hibernate.cacheable", true);
		Long count = (Long)queryCount.getSingleResult();
		
		// Step4: 封装page
		Page<LogDto> page = new PageImpl<>(resultList, PageRequest.of(pageNo, pageSize), count);
		return page;
	
	}
	
}
